import traceback
import os
import utils


EVENT_IQ = 0x01
EVENT_PRESENCE = 0x02
EVENT_MESSAGE = 0x03
EVENT_RAWSTREAM = 0x04

EVENT_STARTUP = 0x001
EVENT_SHUTDOWN = 0x002

EVENT_INITCONFERENCE = 0x003
EVENT_FREECONFERENCE = 0x004

EVENT_SELFMSG = 0x005

EVENT_USERONLINE = 0x006
EVENT_USEROFFLINE = 0x007

CMD_ROSTER   = 0x1
CMD_CHAT     = 0x2
CMD_ANY      = 0x3
CMD_PARAM    = 0x8
CMD_NONPARAM  = 0x10

H_CONFERENCE = 0x001
H_ROSTER = 0x002

Commands = {}
Events   = {}

class PluginWrapper(object):
	__slots__=("handle","access","doc","example","cmdType","__name__")
	def __init__(self,handle,name,access,doc,example,cmdType = CMD_ANY):
		self.__name__ = name
		self.handle = handle
		self.access = access
		self.doc = doc
		self.example = example
		self.cmdType = cmdType
	def __call__(self,*args,**kwargs):
		return self.handle(*args,**kwargs)

def isCommand(command):
	return command in Commands

def getEvents(evtType):
	events = Events.get(evtType)
	if events:
		return iter(events)
	return []

def registryCommand(function, name, access, doc, example, cmdType = CMD_ANY):
	Commands[name]=PluginWrapper(function,name,access,doc,example,cmdType)

def registryEvent(function, eventType):
	if not Events.has_key(eventType):
		Events[eventType] = []
	Events[eventType].append(function)

def LoadPlugins(PLUGINS_DIR):
	for plugin in os.listdir(PLUGINS_DIR):
		path = os.path.join(PLUGINS_DIR, plugin)
		if os.path.isfile(path) and path.endswith('.py'):
			try:
				execfile(path, globals())
			except (NameError,SyntaxError):
				print traceback.format_exc()
